<template>
  <div class="card">
    <!-- 评论主体 -->
    <div class="flex gap-3">
      <!-- 用户头像 -->
      <div class="flex-shrink-0 cursor-pointer" @click="goUserPage">
        <UiAvatar :src="comment.user.avatar" :name="comment.user.name" size="md" />
      </div>
      
      <!-- 评论内容 -->
      <div class="flex-1">
        <!-- 用户信息和时间 -->
        <div class="flex items-center gap-2 mb-2">
          <span class="text-text-primary font-semibold cursor-pointer hover:text-primary-400 transition-colors" @click="goUserPage">
            {{ comment.user.name }}
          </span>
          <span v-if="comment.user.isAi && showAiLabel" class="ai-badge">
            AI
          </span>
          <span class="text-text-muted text-sm">{{ formatTime(comment.createdAt) }}</span>
        </div>
        
        <!-- 评论内容 -->
        <div class="text-text-secondary leading-relaxed mb-3 whitespace-pre-wrap">{{ comment.content }}</div>
        
        <!-- 交互按钮 -->
        <div class="flex items-center gap-4 text-sm">
          <div class="flex items-center gap-1">
            <UiButton 
              @click="handleLike"
              variant="ghost"
              size="sm"
              :class="[
                'p-0 h-auto transition-all duration-200',
                (comment as any).userVote === 1 
                  ? 'text-green-300 font-semibold' 
                  : 'text-text-muted hover:text-green-300'
              ]"
            >
              <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                <path d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z"/>
              </svg>
              <span>{{ comment.likes }}</span>
            </UiButton>
          </div>
          
          <div class="flex items-center gap-1">
            <UiButton 
              @click="handleDislike"
              variant="ghost"
              size="sm"
              :class="[
                'p-0 h-auto transition-all duration-200',
                (comment as any).userVote === -1 
                  ? 'text-red-300 font-semibold' 
                  : 'text-text-muted hover:text-red-300'
              ]"
            >
              <svg class="w-4 h-4 mr-1" fill="currentColor" viewBox="0 0 20 20">
                <path d="M18 9.5a1.5 1.5 0 11-3 0v-6a1.5 1.5 0 013 0v6zM14 9.667v-5.43a2 2 0 00-1.105-1.79l-.05-.025A4 4 0 0011.055 2H5.64a2 2 0 00-1.962 1.608l-1.2 6A2 2 0 004.44 12H8v4a2 2 0 002 2 1 1 0 001-1v-.667a4 4 0 01.8-2.4L13.2 12.067a4 4 0 00.8-2.4z"/>
              </svg>
              <span>{{ comment.dislikes }}</span>
            </UiButton>
          </div>
          
          <UiButton 
            @click="handleReplyClick"
            variant="ghost"
            size="sm"
            class="text-text-muted hover:text-text-primary p-0 h-auto"
          >
            回复
          </UiButton>
          
          <UiButton 
            v-if="comment.replyCount && comment.replyCount > 0"
            @click="toggleReplies"
            variant="ghost"
            size="sm"
            class="text-text-muted hover:text-text-primary p-0 h-auto"
          >
            {{ showReplies ? '隐藏回复' : `查看回复 (${comment.replyCount})` }}
          </UiButton>
        </div>
        
        <!-- 回复输入框 -->
        <div v-if="showReplyInput" class="mt-3">
          <div class="flex gap-2">
            <input 
              v-model="replyContent"
              placeholder="写下你的回复..."
              class="input flex-1 text-sm"
              :disabled="submittingReply"
              @keyup.enter="submitReply"
            />
            <UiButton 
              @click="submitReply"
              :disabled="!replyContent.trim() || submittingReply"
              variant="primary"
              size="sm"
            >
              {{ submittingReply ? '回复中...' : '回复' }}
            </UiButton>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 回复列表 -->
    <div v-if="showReplies && replies.length > 0" class="mt-4 ml-13 space-y-3">
      <div 
        v-for="reply in replies" 
        :key="reply.id"
        class="bg-background-700 rounded-lg p-3"
      >
        <div class="flex items-center gap-2 mb-2">
          <div class="cursor-pointer" @click="goToUser(reply.user.id)">
            <UiAvatar :src="reply.user.avatar" :name="reply.user.name" size="sm" />
          </div>
          <span class="text-text-primary font-semibold text-sm cursor-pointer hover:text-primary-400 transition-colors" @click="goToUser(reply.user.id)">
            {{ reply.user.name }}
          </span>
          <span v-if="reply.user.isAi && showAiLabel" class="ai-badge">
            AI
          </span>
          <span class="text-text-muted text-xs">{{ formatTime(reply.createdAt) }}</span>
        </div>
        <div class="text-text-secondary text-sm whitespace-pre-wrap">{{ reply.content }}</div>
        
        <!-- 回复的交互按钮 -->
        <div class="flex items-center gap-3 mt-2 text-xs">
          <div class="flex items-center gap-1">
            <UiButton 
              @click="handleReplyLike(reply.id)"
              variant="ghost"
              size="sm"
              :class="[
                'p-0 h-auto transition-all duration-200',
                (reply as any).userVote === 1 
                  ? 'text-green-300 font-semibold' 
                  : 'text-text-muted hover:text-green-300'
              ]"
            >
              <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                <path d="M2 10.5a1.5 1.5 0 113 0v6a1.5 1.5 0 01-3 0v-6zM6 10.333v5.43a2 2 0 001.106 1.79l.05.025A4 4 0 008.943 18h5.416a2 2 0 001.962-1.608l1.2-6A2 2 0 0015.56 8H12V4a2 2 0 00-2-2 1 1 0 00-1 1v.667a4 4 0 01-.8 2.4L6.8 7.933a4 4 0 00-.8 2.4z"/>
              </svg>
              <span>{{ reply.likes }}</span>
            </UiButton>
          </div>
          
          <div class="flex items-center gap-1">
            <UiButton 
              @click="handleReplyDislike(reply.id)"
              variant="ghost"
              size="sm"
              :class="[
                'p-0 h-auto transition-all duration-200',
                (reply as any).userVote === -1 
                  ? 'text-red-300 font-semibold' 
                  : 'text-text-muted hover:text-red-300'
              ]"
            >
              <svg class="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                <path d="M18 9.5a1.5 1.5 0 11-3 0v-6a1.5 1.5 0 013 0v6zM14 9.667v-5.43a2 2 0 00-1.105-1.79l-.05-.025A4 4 0 0011.055 2H5.64a2 2 0 00-1.962 1.608l-1.2 6A2 2 0 004.44 12H8v4a2 2 0 002 2 1 1 0 001-1v-.667a4 4 0 01.8-2.4L13.2 12.067a4 4 0 00.8-2.4z"/>
              </svg>
              <span>{{ reply.dislikes }}</span>
            </UiButton>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 加载回复状态 -->
    <div v-if="loadingReplies" class="mt-4 ml-13 text-center py-2">
      <div class="text-text-muted text-sm">加载回复中...</div>
    </div>
    
    <!-- 没有回复提示 -->
    <div v-if="showReplies && replies.length === 0 && !loadingReplies" class="mt-4 ml-13 text-center py-2">
      <div class="text-text-muted text-sm">还没有回复</div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../store/useUserStore'
import { storeToRefs } from 'pinia'
import type { Comment } from '../../types/ui'
import { UiButton, UiAvatar } from '../ui'
import { useCommentReplies } from '../../composables/comments/useCommentReplies'
import { useUiStore } from '../../store/useUiStore'

const props = defineProps<{
  comment: Comment
  movieId?: number // 添加movieId属性
}>()

const emit = defineEmits<{
  reply: [commentId: number, replyContent: string]
  like: [commentId: number]
  dislike: [commentId: number]
  loadReplies: [commentId: number]
}>()

const router = useRouter()
const userStore = useUserStore()
const { isAuthenticated } = storeToRefs(userStore)
const uiStore = useUiStore()
const showAiLabel = computed(() => uiStore.showAiLabel)

// 使用回复composable
const {
  replies,
  loading: loadingReplies,
  error: replyError,
  loadReplies: loadRepliesData,
  submitReply: submitReplyToDb,
  likeReply: likeReplyData,
  dislikeReply: dislikeReplyData
} = useCommentReplies(props.comment.id)

const showReplyInput = ref(false)
const showReplies = ref(false)
const replyContent = ref('')
const submittingReply = ref(false)

const formatTime = (dateString: string): string => {
  const date = new Date(dateString)
  const now = new Date()
  const diff = now.getTime() - date.getTime()
  
  const minutes = Math.floor(diff / (1000 * 60))
  const hours = Math.floor(diff / (1000 * 60 * 60))
  const days = Math.floor(diff / (1000 * 60 * 60 * 24))
  
  if (minutes < 60) {
    return `${minutes}分钟前`
  } else if (hours < 24) {
    return `${hours}小时前`
  } else if (days < 7) {
    return `${days}天前`
  } else {
    return date.toLocaleDateString()
  }
}

const goUserPage = () => {
  router.push({ name: 'UserProfile', params: { id: props.comment.user.id } })
}

const goToUser = (userId: string) => {
  router.push({ name: 'UserProfile', params: { id: userId } })
}

const handleLike = () => {
  if (!isAuthenticated.value) {
    userStore.openLoginModal()
    return
  }
  emit('like', props.comment.id)
}

const handleDislike = () => {
  if (!isAuthenticated.value) {
    userStore.openLoginModal()
    return
  }
  emit('dislike', props.comment.id)
}

const handleReplyClick = () => {
  if (!isAuthenticated.value) {
    userStore.openLoginModal()
    return
  }
  showReplyInput.value = !showReplyInput.value
}

const toggleReplies = async () => {
  if (!showReplies.value && props.comment.replyCount && props.comment.replyCount > 0) {
    // 加载回复
    await loadRepliesData()
  }
  showReplies.value = !showReplies.value
}

const submitReply = async () => {
  if (replyContent.value.trim() && !submittingReply.value) {
    submittingReply.value = true
    try {
      console.log('提交回复:', {
        commentId: props.comment.id,
        content: replyContent.value
      })
      
      // 使用回复composable提交
      const success = await submitReplyToDb(replyContent.value, props.movieId)
      if (success) {
        replyContent.value = ''
        showReplyInput.value = false
        // 提交回复后显示回复列表
        showReplies.value = true
        // 通知父组件刷新评论列表
        emit('reply', props.comment.id, '')
      } else {
        console.error('回复提交失败:', replyError.value)
      }
    } finally {
      submittingReply.value = false
    }
  }
}

const handleReplyLike = async (replyId: number) => {
  if (!isAuthenticated.value) {
    userStore.openLoginModal()
    return
  }
  const result = await likeReplyData(replyId)
  if (result.success) {
    // 实时更新回复的UI状态
    const reply = replies.value.find(r => r.id === replyId)
    if (reply) {
      if (result.action === 'added') {
        // 添加点赞
        reply.likes++
        ;(reply as any).userVote = 1
      } else if (result.action === 'removed') {
        // 取消点赞
        reply.likes--
        ;(reply as any).userVote = 0
      } else if (result.action === 'updated') {
        // 从点踩改为点赞
        reply.dislikes--
        reply.likes++
        ;(reply as any).userVote = 1
      }
    }
  }
}

const handleReplyDislike = async (replyId: number) => {
  if (!isAuthenticated.value) {
    userStore.openLoginModal()
    return
  }
  const result = await dislikeReplyData(replyId)
  if (result.success) {
    // 实时更新回复的UI状态
    const reply = replies.value.find(r => r.id === replyId)
    if (reply) {
      if (result.action === 'added') {
        // 添加点踩
        reply.dislikes++
        ;(reply as any).userVote = -1
      } else if (result.action === 'removed') {
        // 取消点踩
        reply.dislikes--
        ;(reply as any).userVote = 0
      } else if (result.action === 'updated') {
        // 从点赞改为点踩
        reply.likes--
        reply.dislikes++
        ;(reply as any).userVote = -1
      }
    }
  }
}
</script>